<template>
  <span class="list">
    <li
      v-for="item in levels"
      :key="item"
      class="item"
      :class="{ 'li-active': selectedOptionId == item }"
      @click="handleChangeSelectOptions(item)"
    >
      {{ item }}
    </li>
  </span>
</template>

<script lang="ts" setup>
  import { defineEmits, ref, watch } from 'vue';
  import Tree from '@/utils/tree';

  const props = defineProps({
    treeData: {
      type: Array,
      default() {
        return [];
      },
    },
    tableRef: {
      type: Object,
      default: null,
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    childrenKeyName: {
      type: String,
      default: 'children',
    },
  });

  const levels = ref();
  const selectedOptionId = ref();
  const tableRefInner = ref();
  const expandedKeys = ref<string[]>([]);
  const emit = defineEmits(['update:modelValue']);
  const toggleRowExpansionStatus = (
    arr: any[],
    level: number,
    isExpand: boolean
  ) => {
    if (tableRefInner.value) {
      arr.forEach((i) => {
        if (i.children) {
          if (level > 1) {
            expandedKeys.value.push(i[props.rowKey]);
            toggleRowExpansionStatus(i.children, level - 1, isExpand);
          }
        }
      });
      emit('update:modelValue', expandedKeys.value);
    }
  };
  const handleChangeSelectOptions = (event: any) => {
    selectedOptionId.value = event;
    expandedKeys.value = [];
    toggleRowExpansionStatus(props.treeData, event, true);
  };

  watch(
    () => props.treeData,
    (newValue: any) => {
      if (newValue) {
        if (newValue && newValue.length) {
          levels.value = Tree.getTreeDeepth(newValue, props.childrenKeyName);
          handleChangeSelectOptions(levels.value);
        } else {
          levels.value = null;
          selectedOptionId.value = 0;
        }
      }
    },
    { immediate: true, deep: true }
  );

  watch(
    () => props.tableRef,
    (newValue: any) => {
      if (newValue) {
        tableRefInner.value = newValue;
      }
    },
    { immediate: true, deep: true }
  );
</script>

<style scoped>
  .list .item {
    text-decoration: none;
    list-style: none;
    display: inline-block;
    width: 22px;
    height: 22px;
    line-height: 22px;
    text-align: center;
    box-sizing: border-box;
    overflow: hidden;
    margin-right: 0;
  }
  .li-active {
    border-radius: 50%;
    background-color: rgb(var(--primary-6));
    color: #ffffff;
  }
</style>
